package com.fs.cv.service.impl;

import com.fs.cv.dao.*;
import com.fs.cv.pojo.pojodao.*;
import com.fs.cv.service.UserService;
import com.fs.cv.utils.MD5Utils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @工程名: SSM教务管理系统项目
 * @描述：
 * @作者: 小梁子
 * @创建时间: 2020-09-28 00:40
 **/
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserDao userDao;
    @Autowired
    TeacherInfoDao teacherInfoDao;
    @Autowired
    HeadmasterDao headmasterDao;
    @Autowired
    RegistrarDao registrarDao;
    @Autowired
    RoleDao roleDao;


    /**
     * 方法描述:用户登录时，shiro判断账户信息，并返回相应信息
     *
     * @param username
     * @param password
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @author 周先华
     * @date 2020/9/28
     */
    @Override
    public Map<String, Object> login(String username, String password, String remember) {
        Map<String, Object> result = new HashMap<>();
        //获取shiro框架认为的当前用户
        Subject cuurentUser = SecurityUtils.getSubject();
        //判断是否已经认证过，认证过，就不需要再次认证了
        if (!cuurentUser.isAuthenticated()) {
            //当没有认证过时，使用用户输入的用户名和密码进行认证
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            if (remember.equals("yes")) {
                token.setRememberMe(true);
            }
            //shiro执行登录操作
            try {
                cuurentUser.login(token);
            } catch (UnknownAccountException e) {
                //用户不存在
                result.put("code", -1);
                result.put("message", "账号错误！");
                return result;
            } catch (IncorrectCredentialsException e) {
                //密码错误
                result.put("code", -2);
                result.put("message", "密码错误！");
                return result;
            } catch (AuthenticationException e) {
                //抛出错误
                e.printStackTrace();
                result.put("code", -3);
                result.put("message", "登录失败！");
                return result;
            }
        }
        User user = (User) cuurentUser.getSession().getAttribute("user");
        result.put("code", 1);
        result.put("message", "登录成功！");
        result.put("user", user);
        return result;
    }


    /**
     * 方法描述:查询用户信息，根据用户名
     *
     * @param username
     * @return com.fs.cv.pojo.User
     * @author 周先华
     * @date 2020/9/28
     */
    @Override
    public User queryUserInfoByUserName(String username) {
        User user = userDao.queryUserInfoByUserName(username);
        return user;
    }

    /**
     * 方法描述:网站的登出功能
     *
     * @param
     * @param
     * @param
     * @param
     * @return void
     * @author 周先华
     * @date 2020/9/29
     */
    @Override
    public void logout() {

        //获取当前用户
        Subject currentUser = SecurityUtils.getSubject();
        //shiro登出后会自动清除cookie，无需手动删除
//        if (code.equals("0")){
//            System.out.println("********cookie删除功能启用************");
//            //安全退出功能
//            Cookie[] cookies = req.getCookies();
//            for ( Cookie c:cookies) {
//                //将对应的cookie的时间设置为零，即实现删除功能
//                if (c.getName().equals("rememberMe")){
//                    c.setMaxAge(1);
//                }
//            }
//        }
        //只是退出功能
        currentUser.logout();
    }

    /**
     * 方法描述:首次查询全部用户信息，以list表形式返回
     *
     * @param
     * @return java.util.List<com.fs.cv.pojo.pojodao.User>
     * @author 周先华
     * @date 2020/10/3
     */
    @Override
    public List<User> queryAllUsers() {
        List<User> users = userDao.queryAllUsers();
        return users;
    }

    @Override
    public Teacher queryTeacherInfoByUserId(int userId) {
        Teacher teacher = teacherInfoDao.queryTeacherInfoByUserId(userId);
        return teacher;
    }

    @Override
    public Headmaster queryHeadmasterInfoByUserId(int userId) {
        Headmaster headmaster = headmasterDao.queryHeadmasterInfoByUserId(userId);
        return headmaster;
    }

    @Override
    public Registrar queryRegistrarInfoByUserId(int userId) {
        Registrar registrar = registrarDao.queryRegistrarInfoByUserId(userId);
        return registrar;
    }


    //添加用户，角色，权限信息
    @Override
    @Transactional
    public boolean addUserInfo(User user, Role role, Teacher teacher, Headmaster headmaster, Registrar registrar) {
        //根据角色名查询角色信息  舍弃
//        Role roleInfoByRoleName = roleDao.queryRoleInfoByRoleName(role.getName());
        //用户密码加密
        String s = MD5Utils.md5Hash(user.getUserPassword(), user.getUserUserName());
        user.setUserPassword(s);
        //user信息添加
        int a = userDao.addUser(user);
//role信息添加，只需添加user-role表即可
        UserRole userRole = new UserRole();
        userRole.setUserId(user.getUserId());
        userRole.setRoleId(role.getRoleId());
        int b = roleDao.addUserRoleInfo(userRole);
        int c = 0, d = 0;
//根据不同角色信息，添加对应表的信息
        switch (role.getName()) {
            case "任课教师":
                //添加teacher表信息
                c = userDao.addTeacherInfo(teacher);
                UserTeacher userTeacher = new UserTeacher();
                userTeacher.setUserId(user.getUserId());
                userTeacher.setTeacherId(teacher.getTeacherId());
                //添加user-teacher表信息
                d = userDao.addUserTeacherInfo(userTeacher);
                teacherInfoDao.updateCourseState(teacher.getCourseId(),1);
                break;
            case "班主任":
                c = userDao.addHeadmaster(headmaster);
                UserHeadmaster userHeadmaster = new UserHeadmaster();
                userHeadmaster.setUserId(user.getUserId());
                userHeadmaster.setHeadmasterId(headmaster.getHeadmasterId());
                d = userDao.addUserHeadmasterInfo(userHeadmaster);
                break;
            case "教务主任":
                c = userDao.addRegistrar(registrar);
                UserRegistrar userRegistrar = new UserRegistrar();
                userRegistrar.setUserId(user.getUserId());
                userRegistrar.setRegistrarId(registrar.getRegistrarId());
                d = userDao.addUserRegistrarInfo(userRegistrar);
                break;
            case "管理员":
                c = 1;
                d = 1;
                break;
            case "学生":
                c = 1;
                d = 1;
                break;
        }
        System.out.println(a + "**********" + b + "*********" + c + "*********" + d);
        int sum = a + b + c + d;
        if (sum > 2) {
            return true;
        }
        return false;
    }

    @Override
    public boolean changeUserDeleted(User user) {
        int a = userDao.changeUserDeleted(user);
        if (a > 0) {

            return true;
        }
        return false;
    }

    @Override
    public User getUserInfoByUserId(int userId) {

        User user = userDao.queryUserInfoByUserId(userId);
        return user;
    }

    @Override
    public boolean updataUserInfo(User user) {
        String s = MD5Utils.md5Hash(user.getUserPassword(), user.getUserUserName());
        user.setUserPassword(s);
        int a = userDao.updataUserInfo(user);
        return a > 0;
    }

    @Override
    public PageInfo<User> getUsersByPage(Integer currentPage, Integer pageSize) {
        //准备拦截mybatis的后续查询
        PageHelper.startPage(currentPage, pageSize);
        List<User> users = userDao.queryAllUsers();
        //计算当前有多少页
        PageInfo<User> userPageInfo = new PageInfo<>(users);
        return userPageInfo;
    }

    @Override
    public List<Course> getFreeCourseId() {
        List<Course> list= teacherInfoDao.queryAllSurplusCourse();
        return list;
    }


}
